package com.i8office.android.zhihuixinwu.ui.schedule;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseFragment;
import com.example.menhoo.toollibrary.common.utils.DisplayUtil;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.event.RefreshCalendarEvent;
import com.i8office.android.zhihuixinwu.module.contract.CalendarContract;
import com.i8office.android.zhihuixinwu.module.presenter.SelfCalendarSettingPresenter;
import com.i8office.android.zhihuixinwu.widget.ItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import view.recyclerview.CommonAdapter;
import view.recyclerview.HeaderAndFooterWrapper;
import view.recyclerview.ViewHolder;

@ActivityFragmentInject(
        contentViewId = R.layout.fragment_self_calendar_setting
)
public class SelfCalendarSettingFragment extends BaseFragment<CalendarContract.SelfCalendarSettingPresenter> implements CalendarContract.SelfCalendarSettingView, CalendarView.OnCalandarChangedListener {
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    private CalendarView mCalendarView;
    private CommonAdapter<EventItem> mAdapter;
    private HeaderAndFooterWrapper wrapper;
    private DayItem mDayItem;

    public static SelfCalendarSettingFragment newInstance(boolean leaderSet) {

        Bundle args = new Bundle();
        args.putBoolean("leaderSet", leaderSet);
        SelfCalendarSettingFragment fragment = new SelfCalendarSettingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.add)
    void add() {
        Intent intent = new Intent(getActivity(), AddEventActivity.class);
        intent.putExtra("date", mCalendarView.getCheckedDate());
        startActivity(intent);
    }

    @Override
    protected void initView(View view) {
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, view);
        mCalendarView = new CalendarView(getActivity());
        mCalendarView.setBackgroundResource(R.color.white);
        mCalendarView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mCalendarView.setOnCalandarChangedListener(this);
        mRefreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), menhoo.com.i8officelibrary.R.color.tab_top_bg));
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getCalendar();
                getEvents();
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new ItemDecoration(getActivity(), 1));
        wrapper = new HeaderAndFooterWrapper(mAdapter = new CommonAdapter<EventItem>(getActivity(), R.layout.item_event) {
            @Override
            protected void convert(ViewHolder holder, final EventItem eventItem, int position) {
                TextView location = holder.getView(R.id.location);
                TextView department = holder.getView(R.id.department);
                setDrawableLeft(location, R.drawable.icon_location);
                setDrawableLeft(department, R.drawable.icon_department);
                location.setText(eventItem.getLocation());
                location.setVisibility(TextUtils.isEmpty(eventItem.getLocation()) ? View.GONE : View.VISIBLE);
                department.setText(eventItem.getDeptName());
                department.setVisibility(TextUtils.isEmpty(eventItem.getDeptName()) ? View.GONE : View.VISIBLE);
                TextView title = holder.getView(R.id.title);
                title.setTextColor(ContextCompat.getColor(mContext, eventItem.getCanEdit() == 0 ? R.color.textcolor3 : R.color.black));
                holder.setText(R.id.title, eventItem.getTitle());
                holder.setText(R.id.time, TextUtils.isEmpty(eventItem.getStartTimeString()) ? "-- : --" : eventItem.getStartTimeString());
                holder.getView(R.id.content).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (eventItem.getCanEdit() == 0) {
                            new MaterialDialog.Builder(mContext)
                                    .title(R.string.hint)
                                    .autoDismiss(true)
                                    .content(eventItem.getDesc())
                                    .positiveText(R.string.modify)
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            Intent intent = new Intent(getActivity(), AddLeaderEventActivity.class);
                                            intent.putExtra("event", eventItem);
                                            intent.putExtra("leaderId", "");
                                            startActivity(intent);
                                        }
                                    })
                                    .negativeColorRes(R.color.textcolor2)
                                    .negativeText(R.string.cancel)
                                    .show();

                        } else {
                            Intent intent = new Intent(getActivity(), AddEventActivity.class);
                            intent.putExtra("event", eventItem);
                            startActivity(intent);
                        }

                    }
                });
                holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new MaterialDialog.Builder(getActivity())
                                .content(R.string.delete_event)
                                .positiveText(R.string.confirm)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                                        mPresenter.removeEvent(eventItem.getTaskID());
                                    }
                                })
                                .negativeText(R.string.cancel)
                                .show();

                    }
                });
            }
        });

        wrapper.addHeaderView(mCalendarView);
        mRecyclerView.setAdapter(wrapper);
        mPresenter = new SelfCalendarSettingPresenter(this);
        mRefreshLayout.setRefreshing(true);
        getCalendar();
    }

    private String getTimeString(int h, int m) {
        StringBuffer sb = new StringBuffer();
        if (h < 10) {
            sb.append("0");
        }
        sb.append(h + ":");
        if (m < 10) {
            sb.append("0");
        }
        sb.append(m);
        return sb.toString();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshCalendarEvent event) {
        getCalendar();
        getEvents();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setDrawableLeft(TextView view, @DrawableRes int drawableRes) {
        Drawable drawable = ContextCompat.getDrawable(getActivity(), drawableRes);
        drawable.setBounds(0, 0, DisplayUtil.dip2px(getActivity(), 12), DisplayUtil.dip2px(getActivity(), 12));
        view.setCompoundDrawables(drawable, null, null, null);
    }

    @Override
    public void showCalendarData(List<DayItem> data) {
        mCalendarView.setData(data);
    }

    @Override
    public void showEventData(List<EventItem> data) {
        mAdapter.setList(data);
        mCalendarView.setEmpty(mAdapter.getItemCount() == 0);
        wrapper.notifyDataSetChanged();
    }

    @Override
    public void deleteSuccess() {
        toast(R.string.delete_success);
        getCalendar();
        getEvents();
        EventBus.getDefault().post(new RefreshCalendarEvent());
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onCheckDate(DayItem item) {
        mDayItem = item;
        getEvents();
    }

    private void getCalendar() {
        mPresenter.getCalendarData(mCalendarView.getCurrentYear(), mCalendarView.getCurrentMonth());

    }

    private void getEvents() {
        if (mDayItem != null) {
            mPresenter.getEventsByDate(mDayItem.getYear(), mDayItem.getMonth(), mDayItem.getDay());
        }
    }

    @Override
    public void onMonthChanged(int year, int month) {
        mPresenter.getCalendarData(year, month);
    }
}
